//
//  UILabel+ZZ.swift
//  ZH_SheQu
//
//  Created by 陈钟 on 2019/12/26.
//  Copyright © 2019 陈钟. All rights reserved.
//

import Foundation
import UIKit

public extension NSObject{
    func objc_set(key: String, _ newValue: Any?,_ policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC){
        let `key`: UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: key.hashValue)
        objc_setAssociatedObject(self, key, newValue, policy)
    }

    func objc_get<T>( key: String, _ type: T.Type) -> T?{
        let `key`: UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: key.hashValue)
        let obj = objc_getAssociatedObject(self, key)
        return obj as? T
    }
}

public extension UILabel{

    var lineHeight: CGFloat{
        get{
            return objc_get(key: "lineHeight", CGFloat.self) ?? 0
        }

        set{
            objc_set(key: "lineHeight", newValue)
            self.text(self.text)
        }
    }

    @discardableResult
    func lineHeight(_ value: CGFloat) -> Self{
        self.lineHeight = value
        return self
    }

    @discardableResult
    func font(_ font: UIFont) -> Self{
        self.font = font
        return self
    }

    @discardableResult
    func attributedText(_ value: NSAttributedString?) -> Self{
        self.attributedText = value
        return self
    }

    @discardableResult
    func numberOfLines(_ value: Int) -> Self{
        self.numberOfLines = value
        return self
    }

    @discardableResult
    func lineBreakMode(_ value: NSLineBreakMode) -> Self{
        self.lineBreakMode = value
        return self
    }

    @discardableResult
    func textColor(_ color: UIColor) -> Self{
        self.textColor = color
        return self
    }

//    @discardableResult
//    func backgroundColor(_ color: UIColor) -> Self{
//        self.backgroundColor = color
//        return self
//    }

    @discardableResult
    func textAlignment(_ alignment: NSTextAlignment) -> Self{
        self.textAlignment = alignment
        return self
    }
    
    @discardableResult
    func text(_ text: String?) -> Self{
        if self.lineHeight == 0{
            self.text = text
        }else{
            guard let value = text else {
                self.text = text
                return self
            }
            let pla = NSMutableParagraphStyle()
            pla.lineSpacing = self.lineHeight
            pla.lineBreakMode = .byTruncatingTail
            pla.alignment = self.textAlignment

            let att = NSMutableAttributedString(string: value)
            att.addAttribute(NSAttributedString.Key.paragraphStyle, value: pla, range: NSRange(location: 0, length: value.count))
            self.attributedText = att
        }
        return self
    }
}
